/*global Drupal, jQuery, Timeline */

Timeline.DefaultEventSource.prototype.nodesLoaded = function(nodes, type) {
  var added = false;
  if (nodes) {
    for (var i = 0; i < nodes.length; i++) {
      var node = nodes[i];
      var publish_time = new Date(node.field_publish_time[0].value * 1000);

      var info = {};
      if(type['eventInfo']) {
        info = type['eventInfo']
      }
      
      var description = '';
      if(info['description']) {
        if(typeof info['description'] == 'function') {
          description = info['description'](node, type);
        }
        else if(node[info['description']]) {
          description = node[info['description']];
        }
        else
          description = info['description'];
      }
      
      var evt = new Timeline.DefaultEventSource.Event(
      publish_time, publish_time, publish_time, publish_time,
      true, node.title, description, null, '/node/' + node.nid,
      info['icon'], null, null);
      evt._obj = node;
      evt.getProperty = function(name) {
          return this._obj[name];
      };

      this._events.add(evt);
      added = true;
    }
  }

  if (added) {
    this._fire("onAddMany", []);
  }
};


var TimedPublishing = function () {
  var stripTime = function(date){
    var date = new Date(date.getTime());
    date.setHours(0,0,0,0);
    return date;
  },
  maxTime = function(date){
    var date = new Date(date.getTime());
    date.setHours(23,59,59);
    return date;
  },
  iso_date = function (date) {
    var idp = function (num, sep) {
      return sep + (num < 10 ? '0' : '') + num;
    };
    
    offset = -date.getTimezoneOffset();
    offset_m = offset % 60;
    offset_h = (offset-offset_m) / 60;
    tz_designator = idp(offset_h, (offset>=0?'+':'')) + idp(offset_m,':');
      
    return date.getFullYear() + idp(date.getMonth() + 1, '-') + idp(date.getDate(), '-') +
      idp(date.getHours(), 'T') + idp(date.getMinutes(), ':') + idp(date.getSeconds(), ':') + tz_designator;
  },
  currentDate = new Date(), 
  maxDate = new Date(), 
  timeline, 
  eventSource,
  contentTypes = [];

  var wheel = function (event, callBack) {
      var delta = 0;
      if (event.wheelDelta) {
          delta = event.wheelDelta/120; 
          if (window.opera) {
              delta = -delta;
          }
      } else if (event.detail) {
          delta = -event.detail/3;
      }
      if (delta) {
          callBack.call(this, delta);
      }

      this.closeBubble();
      Timeline.DOM.cancelEvent(event);
      return false;
    };
  
  return {
    initTimeline : function (placeholder_id) {
      eventSource = new Timeline.DefaultEventSource();
      
      var bandInfos = [
          Timeline.createBandInfo({
            width:          "40%",
            eventSource:    eventSource,
            intervalUnit:   Timeline.DateTime.HOUR, 
            timeZone:       -Math.round(new Date().getTimezoneOffset()/60),
            intervalPixels: 300
          }),
          Timeline.createBandInfo({
            width:          "60%",
            eventSource:    eventSource,
            intervalUnit:   Timeline.DateTime.DAY, 
            timeZone:       -Math.round(new Date().getTimezoneOffset()/60),
            intervalPixels: 300
          })
        ];
    
      bandInfos[1].syncWith = 0;
      bandInfos[1].highlight = true;
      
      timeline = Timeline.create(document.getElementById(placeholder_id), bandInfos);
      var time_band  = timeline.getBand(0),
          date_band = timeline.getBand(1);

      var scrollwheel = function (keyboardInput, evt, target) {
        return wheel.call(this, evt, function(delta) {
          if (delta > 0) {
            this._moveEther(50);
          } else {
            this._moveEther(0 - 50);
          }
        });
      };
      
      Timeline.DOM.registerEventWithObject(time_band._div,  "mousewheel", time_band,  scrollwheel);
      Timeline.DOM.registerEventWithObject(date_band._div, "mousewheel", date_band, scrollwheel);
      Timeline.DOM.registerEventWithObject(time_band._div,  "DOMMouseScroll", time_band,  scrollwheel);
      Timeline.DOM.registerEventWithObject(date_band._div, "DOMMouseScroll", date_band, scrollwheel);
      
      date_band.addOnScrollListener(function (band) {
        jQuery(document).trigger('timedpublishing_change', [band.getCenterVisibleDate(), band.getMaxVisibleDate()]);
      });

      jQuery(document).bind('timedpublishing_change', function (e, current, date) {
        TimedPublishing.setTime(current, date);
      }).trigger('timedpublishing_change', [date_band.getCenterVisibleDate(), date_band.getMaxVisibleDate()]);;
    },
    setTime : function (current, date) {
      if ((date > maxDate && date.getDate() !== maxDate.getDate())) {
        maxDate = date;
        this.load();
      }
    },
    addContentType : function (type, eventInfo, fields, imagecache) {
      contentTypes.push({'type': type, 'eventInfo': eventInfo, 'fields': fields, 'imagecache': imagecache});
    },
    load : function () {
      var typeCount = contentTypes.length;
      
      for(var i=0; i<typeCount; i++) {
        Drupal.service(
          'timed_publishing.interval',
          { 
            from: iso_date(stripTime(currentDate)), 
            to: iso_date(maxTime(maxDate)),
            type: contentTypes[i]['type'],
            fields: contentTypes[i]['fields'],
            filters: contentTypes[i]['imagecache']
          },
          function (type, eventSource) {
            return function (result, error, id) {
              if (error) {
                alert(error.message);
              }
              else if (result.length !== 0) {
                eventSource.nodesLoaded(result, type);
                jQuery(document).trigger('timedpublishing_loaded', [result, type]);
              }
            }
          }(contentTypes[i], eventSource)
        );
      }
      
      currentDate = new Date(maxDate.getTime()+86400000);
    }
  };
}();
